import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:sph_shipper/AppConfig/ShowDialog.dart';

import '../../AppConfig/LocalStorage.dart';
import '../../TabBar/TabbarView.dart';
import '../../http/api.dart';

class DepositRefundView extends StatefulWidget {
  const DepositRefundView({super.key, required this.billData});
  final Map billData;

  @override
  State<DepositRefundView> createState() => _DepositRefundViewState();
}

class _DepositRefundViewState extends State<DepositRefundView> {
  int isShow=0;
  int checkType=-1;
  String message="";
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text("退还订金",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
      ),
      body: Column(
          children: [
            Expanded(child: ListView(children: [
              Container(
              margin:EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            padding: EdgeInsets.only(left: 12.w,top: 16.h,bottom: 16.h,right: 12.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text("订金金额",style: TextStyle(color: Colors.black),),
                    Text("¥"+(widget.billData['deposit']).toStringAsFixed(2),style: TextStyle(color: Colors.black),),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 22.w,top: 8.h,),
                child: Row(
                  children: [
                    Text("请选择退还原因",style: TextStyle(color: Colors.black),),
                    Text("（必选）",style: TextStyle(color: MyColors.textColor),),
                  ],
                ),
              ),
              Container(
                margin:EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(left: 11.w,top: 9.h,bottom: 11.h,right: 11.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular( (10)),),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset("lib/Images/OrderList/退还订金运单icon.png",width: 24.w,height: 24.h,),
                        SizedBox(width: 8.w,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("运单原因",style: TextStyle(color: Colors.black,),),
                            Text("保持良好的履约行为会让您的信用更高，走货更快",style: TextStyle(color: MyColors.themeColor,fontSize: 10.sp),),
                          ],
                        ),

                      ],
                    ),
                    GestureDetector(
                      child: Icon(isShow==0?Icons.keyboard_arrow_down: Icons.keyboard_arrow_up,size: 30,color: MyColors.authTipColor,),
                      onTap: (){
                      setState(() {
                        isShow==0?isShow=1:isShow=0;
                      });
                      },
                    ),
                  ],
                ),
            ),
              if(isShow==1)
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w),
                padding: EdgeInsets.only(left: 11.w,top: 14.h,bottom: 14.h,right: 11.w),
                decoration: BoxDecoration(
                  color: Color.fromRGBO(239, 239, 239, 1),
                  borderRadius: BorderRadius.only( bottomLeft:Radius.circular(10),bottomRight: Radius.circular(10)),),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("已经装货，退还订金",style: TextStyle(color: Colors.black),),
                        GestureDetector(
                          child: Icon(checkType==1?Icons.check_circle: Icons.circle_outlined,color:checkType==1?MyColors.themeColor: MyColors.authTipColor,),
                          onTap: (){
                            setState(() {
                              checkType=1;
                              message="已经装货，退还订金";
                            });
                          },
                        )
                      ],
                    ),
                    SizedBox(height: 17.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("货已送达，退还订金",style: TextStyle(color: Colors.black),),
                        GestureDetector(
                          child: Icon(checkType==2?Icons.check_circle: Icons.circle_outlined,color:checkType==2?MyColors.themeColor: MyColors.authTipColor,),
                          onTap: (){
                            setState(() {
                              checkType=2;
                              message="货已送达，退还订金";
                            });
                          },
                        )
                      ],
                    ),
                    SizedBox(height: 17.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("已线下支付运费，退还订金",style: TextStyle(color: Colors.black),),
                        GestureDetector(
                          child: Icon(checkType==3?Icons.check_circle: Icons.circle_outlined,color:checkType==3?MyColors.themeColor: MyColors.authTipColor,),
                          onTap: (){
                            setState(() {
                              checkType=3;
                              message="已线下支付运费，退还订金";
                            });
                          },
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ],
            ),
            ),
            Container(
              height: 85.h,
              color: Colors.white,
              padding: EdgeInsets.only(left: 23.w,right: 11.w,top: 14.h,bottom: 40.h),
              child: BrnSmallMainButton(
                title: '提交',
                fontSize: 16.sp,
                bgColor: MyColors.themeColor,
                textColor: Colors.white,
                fontWeight: FontWeight.w600,
                radius: 30,
                width: screenSize.width-30.w,
                onTap: ()  {
                  if(message==""){
                    BrnToast.show("请选择退还原因", context);
                  }else{
                    BrnDialogManager.showConfirmDialog(context,
                        title: "提示",
                        message:"确认退还订金吗？",
                        cancel: "",
                        cancelWidget: GestureDetector(
                          child: Center(
                            child:  Text("我再想想",style: TextStyle(color: Colors.black),),
                          ),
                          onTap: (){
                            Navigator.pop(context);
                          },
                        ),
                        conformWidget:GestureDetector(
                          child: Center(
                            child:  Text("确认",style: TextStyle(color: MyColors.themeColor),),
                          ),
                          onTap: () async {
                            LoadingDialog.show(context);
                            String? token = await TokenManager.getToken();
                            dio.interceptors.add(InterceptorsWrapper(
                                onRequest: (options, handler) {
                                  options.headers["satoken"] = token;
                                  return handler.next(options);
                                }
                            ));
                            dio.post(
                              MyServiceUrl.header+'api/waybill/waybill/shipper/returnDeposit',
                              data: {
                            "waybillId":widget.billData['waybillId'],
                            "message":message,
                            },
                              options: Options(
                                sendTimeout: Duration(seconds: 2),
                                receiveTimeout: Duration(seconds: 50),
                              ),
                              onSendProgress: (a, b) => print('send ${a / b}'),
                              onReceiveProgress: (a, b) =>
                                  print('received ${a / b}'),
                            )
                                .then((r) {
                              setState(() {
                                print(r);
                                Map<String, dynamic> jsonMap = json.decode(
                                    r.toString());
                                // 获取code和data
                                String code = jsonMap['code'].toString();
                                if (code == "200") {
                                  LoadingDialog.hide(context);
                                  Navigator.pop(context);
                                  Navigator.pushReplacement(
                                    context,
                                    MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                                  );
                                }else{
                                  LoadingDialog.hide(context);
                                  BrnToast.show(jsonMap['msg'], context);
                                }
                              });
                            }).catchError((error) {
                              print(error);
                              ;
                            });
                          },
                        ),
                        confirm:"", onConfirm: () {}, onCancel: () {
                        });

                  }

                },
              ),
            )
          ],
      ),
    );
  }
}
